package leetcode.p15;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 * @author: trtan
 * @date: 2021-06-29 13:10
 **/
public class ThreeSum {
    public static void main(String[] args) {
        List<List<Integer>> list = new ThreeSum().threeSum(new int[]{-1, 0, 1, 2, -1, -4});
        for (int i = 0; i < list.size(); i++) {
            for (Integer j : list.get(i)) {
                System.out.print(j + ", ");
            }
            System.out.println();
        }
    }
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        // 枚举a b c
        int n = nums.length;
        for (int a = 0; a < n; a++) {
            if (a > 0 && nums[a] == nums[a - 1]) {
                continue;
            }
            int c = n - 1;
            int target = -nums[a];
            for (int b = a + 1; b < n; b++) {
                if (b > a + 1 && nums[b] == nums[b - 1]) {
                    continue;
                }
                while (b < c && nums[b] + nums[c] > target) {
                    c--;
                }
                if (b == c) {
                    break;
                }
                if (b < c && nums[b] + nums[c] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[a]);
                    list.add(nums[b]);
                    list.add(nums[c]);
                    result.add(list);
                }
            }
        }
        return result;
    }
}
